package com.sms.web.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.commons.lang3.StringUtils	;

/**
 * @desc 系统初始化环境
 * @author WuJiangWu
 * @date 2018年7月15日
 */
public abstract class WebUtils {
	
	private static Logger logger = Logger.getLogger(WebUtils.class.getName());
    
    /** 默认编码 UTF-8 */
    public static final String DEFAULT_CHARSET = "UTF-8";
    /** web 应用上下文路径 */
    public static volatile String webAppContextPath = null;
    /** web 应用真实路径 */
    public static volatile String webAppRealPath = null;
    
    /** webRoot web 应用上下文路径 */
    public static void initWebRootOnce(String webRoot) {
        if (webAppContextPath == null) {
            webAppContextPath = webRoot;
        }
    }
    
    /** web 应用上下文路径 */
    public static String getWebRoot() {
        return webAppContextPath;
    }
    
    /** realPath web 应用真实路径  */
    public static void initWebRealPathOnce(String realPath) {
        if (webAppRealPath == null) {
            webAppRealPath = realPath;
        }
    }
    
    /** web 应用真实路径 */
    public static String getWebRealPath() {
        return webAppRealPath;
    }
    
    
    /**
     * 使用默认的UTF-8字符集反编码请求参数值。
     * @param value 参数值
     * @return 反编码后的参数值
     */
    public static String decode(String value) {
        return decode(value, DEFAULT_CHARSET);
    }
    
    /**
     * 使用默认的UTF-8字符集编码请求参数值。
     * @param value 参数值
     * @return 编码后的参数值
     */
    public static String encode(String value) {
        return encode(value, DEFAULT_CHARSET);
    }
    
    /**
     * 使用指定的字符集反编码请求参数值。
     * @param value 参数值
     * @param charset 字符集
     * @return 反编码后的参数值
     */
    public static String decode(String value, String charset) {
        String result = null;
        if (!StringUtils.isEmpty(value)) {
            try {
                result = URLDecoder.decode(value, charset);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }
    
    /**
     * 使用指定的字符集编码请求参数值。
     * @param value 参数值
     * @param charset 字符集
     * @return 编码后的参数值
     */
    public static String encode(String value, String charset) {
        String result = null;
        if (!StringUtils.isEmpty(value)) {
            try {
                result = URLEncoder.encode(value, charset);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return result;
    }
    
    /**
     * 从URL中提取所有的参数。
     * @param query URL地址
     * @return 参数映射
     */
    public static Map<String, String> splitUrlQuery(String query) {
        Map<String, String> result = new HashMap<String, String>();
        
        String[] pairs = query.split("&");
        if (pairs != null && pairs.length > 0) {
            for (String pair : pairs) {
                String[] param = pair.split("=", 2);
                if (param != null && param.length == 2) {
                    result.put(param[0], param[1]);
                }
            }
        }
        return result;
    }
    
    public static String executePost(String httpurl, Map<String, String> params) throws Exception{
    	StringBuffer log = new StringBuffer();
    	log.append("===================httppsot-begin===========================\r\n");
    	log.append("  url = "+httpurl);
    	try {
	    	URL url = new URL(httpurl);// 创建连接  
	        HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
	        connection.setDoOutput(true);
	        connection.setDoInput(true);
	        connection.setUseCaches(false);  
	        connection.setInstanceFollowRedirects(true);
	        connection.setRequestMethod("POST"); // 设置请求方式  
	        connection.setRequestProperty("User-Agent", "SmsClinet-SDK");
	        connection.setRequestProperty("Accept", "application/json");// 设置接收数据的格式  
	        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // 设置发送数据的格式  
	        connection.connect();
	        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
	        StringBuffer body = new StringBuffer();
	        for( String key : params.keySet() ) {
	        	body.append("&"+key+"="+URLEncoder.encode(params.get(key), "utf-8"));
	        	log.append("  "+key+" = "+params.get(key)+"\\r\\n");
	        }
	        out.append(body.substring(1)); 
	        out.flush();  
	        out.close();
	        InputStream inputStream = connection.getInputStream();  
	        //对应的字符编码转换  
	        Reader reader = new InputStreamReader(inputStream, "UTF-8");  
	        BufferedReader bufferedReader = new BufferedReader(reader);  
	        String str = null;
	        StringBuffer sb = new StringBuffer();  
	        while ((str = bufferedReader.readLine()) != null) {  
	            sb.append(str);  
	        }
	        reader.close();
	        String resultBody = sb.toString();
	        Integer code = connection.getResponseCode();
	        if ( code != 200){
	            logger.log(Level.INFO, "发送结果：" + resultBody);
	            throw new Exception("(" + code + ")http请求失败！");
	        }
	        connection.disconnect();
	        return sb.toString();
    	} catch (IOException e) {
    		 throw new Exception("http请求异常！");
        }finally {
        	log.append("===================httppsot-end=============================");
        	System.out.println(log.toString());
		}
    }
    
}
